package com.family.gmall.product.controller;

import com.family.gmall.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.message.ReusableMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @Auther: family
 * @Date: 2023/7/11 10:35
 * @Description:
 */
@RestController
@RequestMapping("/admin/product")
public class FileUploadController {
    //  获取文件上传对应的地址
    @Value("${minio.endpointUrl}")
    public String endpointUrl;

    @Value("${minio.accessKey}")
    public String accessKey;

    @Value("${minio.secreKey}")
    public String secreKey;

    @Value("${minio.bucketName}")
    public String bucketName;

    @ApiOperation("上传文件控制器")
    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception {
        String url = "";
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpointUrl)
                .credentials(accessKey, secreKey)
                .build();

        boolean exists = minioClient.bucketExists(BucketExistsArgs
                .builder().bucket(bucketName).build());
        if (exists) {
            System.out.println("Bucket already exists.");
        } else {
            minioClient.makeBucket(MakeBucketArgs
                    .builder().bucket(bucketName).build());
        }

        String fileName = System.currentTimeMillis() + UUID.randomUUID().toString();

        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .contentType(file.getContentType())//不说内容类型，默认浏览器下载
                        .object(fileName).stream(
                                file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        url = endpointUrl + "/" + bucketName + "/" + fileName;
        System.out.println("url:\t" + url);
        return Result.ok(url);
    }

}
